import { reactive } from "vue";
import {
  WritablePaginationProps,
  ZPaginationOptions,
  ZTableMethods,
} from "../typings";

export const defaultPaginationConfig = {
  defaultPage: 1,
  defaultPageSize: 10,
  pageSizes: [5, 10, 20, 25, 50, 100, 200],
  showQuickJumper: true,
  showSizePicker: true,
  showTotal: true,
  pageCount: 1,
};

export function usePagination(
  options: ZPaginationOptions | false | undefined,
  methods: ZTableMethods
): WritablePaginationProps | false {
  if (options === false) return false;

  const { showTotal = true, ...rest } = {
    ...defaultPaginationConfig,
    ...options,
  };
  const pagination = reactive<WritablePaginationProps>({
    ...rest,
    prefix: (info) => (showTotal ? `共 ${info.itemCount} 条` : undefined),
    onUpdatePage(page) {
      pagination.page = page;
      methods.fetchDataSource();
    },
    onUpdatePageSize(pageSize) {
      pagination.pageSize = pageSize;
      methods.fetchDataSource();
    },
    page: rest.defaultPage,
    pageSize: rest.defaultPageSize,
    pageCount: rest.pageCount,
  });

  return pagination;
}
